import * as Cesium from '@cesiumjs';
import {
  createImageProvider
} from "./imageryProvider";

const EMPTY_OBJECT = {};

function updateImageLayerByOptions(imageLayer, opts) {
  if (imageLayer) {
    opts = opts || EMPTY_OBJECT;
    opts = opts.options || opts; // lyrDefine.options
    for (let k in opts) {
      imageLayer.hasOwnProperty(k) && (imageLayer[k] = opts[k])
    }
  }
}

function updateImageLayerTitle(lyr, lyrDefine) {
  if (lyr) {
    lyrDefine = lyrDefine || EMPTY_OBJECT;
    const imageryProvider = lyr.imageryProvider;
    Object.defineProperty(lyr, "name", {
      get() {
        return lyr._name || lyrDefine.name || imageryProvider.name || "未命名"
      },
      set(val) {
        lyr._name = val
      }
    })
    Object.defineProperty(lyr, "title", {
      get() {
        return lyr._title || lyrDefine.title || imageryProvider.title || lyr.name
      },
      set(val) {
        lyr._title = val
      }
    })
    !lyr.guid && (lyr.guid = Cesium.createGuid());
  }
}

function addImageLayer(viewer, lyrDefine) {
  if (lyrDefine) {
    const imageryProvider = createImageProvider(lyrDefine, viewer);
    const lyr = imageryProvider && viewer.imageryLayers.addImageryProvider(imageryProvider);
    lyr && imageryProvider.setLayer && imageryProvider.setLayer(lyr); // for graticule
    updateImageLayerByOptions(lyr, lyrDefine)
    updateImageLayerTitle(lyr, lyrDefine)
    return lyr;
  }
}

var utils = {
  createImageProvider,
  addImageLayer,
  updateImageLayerByOptions,
  updateImageLayerTitle
};

utils.initAddLayers = (viewer, lyrDefines) => {
  if (viewer && lyrDefines) {
    lyrDefines.forEach(e => addImageLayer(viewer, e))
  }
}

export default utils;
